import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:get/get.dart';
import 'package:mobx/mobx.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:terminal_flutter_demo/font/CustomIcon.dart';
import 'package:terminal_flutter_demo/generated/l10n.dart';
import 'package:terminal_flutter_demo/pages/mobxpages/preferences/preferences_service.dart';
import 'package:terminal_flutter_demo/pages/mobxpages/store/mobx_counter.dart';
import 'package:terminal_flutter_demo/pages/mobxpages/store/mobx_test.dart';
import 'package:terminal_flutter_demo/routers/getx_routes.dart';
import 'package:terminal_flutter_demo/store/app.dart';
import 'package:terminal_flutter_demo/widgets/my_drawer.dart';

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  HttpOverrides.global = MyHttpOverrides();

  // 数据持久化
  final sharedPreferences = await SharedPreferences.getInstance();

  // ignore: avoid_print
  mainContext.spy(print);

  runApp(MyApp(sharedPreferences));
}

class MyApp extends StatelessWidget {
  MyApp(this.sharedPreferences, {super.key});

  final SharedPreferences sharedPreferences;

  final GlobalKey<ScaffoldState> _scaffoldWidgetKey =
      GlobalKey<ScaffoldState>();

  get _navigationBarItems {
    return [
      const BottomNavigationBarItem(
        icon: Icon(
          Icons.home,
        ),
        label: '主页',
      ),
      const BottomNavigationBarItem(
        icon: Icon(
          CustomIcon.weixin,
        ),
        label: '微信',
      ),
      const BottomNavigationBarItem(
        icon: Icon(
          Icons.search,
        ),
        label: '搜索',
      ),
      const BottomNavigationBarItem(
        icon: Icon(
          CustomIcon.gouwuchekong,
        ),
        label: '购物车',
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<MobxTest>(create: (_) => MobxTest()),
        Provider<MobxCounter>(create: (_) => MobxCounter()),
        Provider<MobxAppStore>(create: (_) => MobxAppStore()),
        Provider<PreferencesService>(
          create: (_) => PreferencesService(sharedPreferences),
        ),
        // ProxyProvider、ProxyProvider2、ProxyProvider3 ...类名后的数字是 ProxyProvider 依赖的 provider 的数量。
        ProxyProvider<PreferencesService, MobxCounter>(
            update: (_, preferencesService, __) =>
                MobxCounter.preferences(preferencesService)),
      ],
      child: Consumer2<MobxCounter, MobxAppStore>(
        builder: (_, mobxCounterStore, mobxAppStore, __) {
          return Observer(
            builder: (context) => GetMaterialApp(
              debugShowCheckedModeBanner: false, // 右上角debug图标是否显示
              localizationsDelegates: const [
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
                S.delegate,
              ],
              supportedLocales: S.delegate.supportedLocales,
              locale: Locale.fromSubtags(
                  languageCode: mobxCounterStore.useLanguage),
              localeListResolutionCallback: (locales, supportedLocales) {
                print('当前系统语言：$locales');
                return Locale.fromSubtags(
                    languageCode: mobxCounterStore.useLanguage);
              },
              // localeResolutionCallback: (locale, supportedLocales) {
              //   print('localeResolutionCallback$locale');
              //   return const Locale.fromSubtags(languageCode: 'zh');
              // },
              theme: ThemeData(
                primaryColor: Colors.blue,
                // canvasColor: Colors.white, // 设置整个程序中所有界面的背景颜色
                brightness: mobxCounterStore.useDarkMode
                    ? Brightness.dark
                    : Brightness.light,
              ),
              initialRoute: '/home',
              defaultTransition: Transition.rightToLeft,
              getPages: GetXRoutes.getPages,
              home: Scaffold(
                key: _scaffoldWidgetKey,
                appBar: AppBar(title: const Text('Flutter')),
                body: mobxAppStore.getShowPage,
                drawer: MyDrawer(
                  widgets: mobxAppStore.widgets,
                  onTap: (Widget widget) {
                    mobxAppStore.isDrawerSwitch = true;
                    mobxAppStore.currendDrawerWidget = widget;
                  },
                ),
                endDrawer: Drawer(
                  child: Column(
                    children: [
                      const Text('右侧抽屉'),
                      const SizedBox(height: 30),
                      ElevatedButton.icon(
                        icon: const Icon(Icons.home),
                        onPressed: () {
                          Get.back();
                          Get.toNamed('/home');
                        },
                        label: const Text('去GetX首页'),
                      ),
                    ],
                  ),
                ),
                bottomNavigationBar: BottomNavigationBar(
                  fixedColor: Colors.greenAccent, // 选中的颜色
                  iconSize: 36,
                  currentIndex: mobxAppStore.currentIndex,
                  type: BottomNavigationBarType.fixed, // 4个或4个以上须设置此属性
                  onTap: (index) {
                    mobxAppStore.isDrawerSwitch = false;
                    mobxAppStore.isNavSwitch = true;
                    mobxAppStore.currentIndex = index;
                  },
                  items: _navigationBarItems,
                ),
                floatingActionButtonLocation:
                    FloatingActionButtonLocation.centerDocked,
                floatingActionButton: Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: Colors.amber,
                    borderRadius: BorderRadius.circular(30),
                    boxShadow: const [
                      BoxShadow(color: Colors.red, blurRadius: 10),
                    ],
                  ),
                  child: FloatingActionButton(
                    onPressed: () {
                      _scaffoldWidgetKey.currentState!.openDrawer();
                      // setState(() {
                      //   _isDrawerSwitch = false;
                      //   _isNavSwitch = false;
                      //   _showIndex++;
                      //   if (_showIndex > widgets.length - 1) {
                      //     _showIndex = 0;
                      //   }
                      // });
                    },
                    child: const Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('切换'),
                        // Text('$showIndex'),
                        // Text(widgets[_showIndex].toString()),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
